package com.fruit.auth.web.action;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fruit.auth.model.Department;
import com.fruit.auth.model.User;
import com.fruit.auth.service.DepartmentService;
import com.fruit.auth.service.impl.ServiceException;
import com.fruit.system.model.Pager;
import com.fruit.web.action.util.BaseAction;
/**
 * 权限控制器
 * @author Administrator
 *
 */
@Controller
@Scope("prototype")
public class DepartmentAction extends BaseAction<Department>
{

	private static final long serialVersionUID = -295844060845230160L;
	private Department department;
	@Resource
	private DepartmentService departmentService;

	@Override
	public Department getModel()
	{
		return department;
	}
	@Override
	public void prepare() throws Exception
	{
		department=new Department();
		department.setParent(new Department());
	}
	
	public String departments()
	{
		List<Department> departments=departmentService.findAllEntity();
		for(Department d:departments)
		{
			d.setPid(d.getParent()==null?0:d.getParent().getId());
			d.setParent(null);
		}
		renderJson(departments);
		return NONE;
	}
	
	public String add()
	{
		if(department.getParent().getId()==null)
			department.setParent(null);
		departmentService.saveEntity(department);
		ajaxMsg.setSuccess(true);
		renderJson(ajaxMsg);
		return NONE;
	}
	
	public String delete()
	{
		try
		{
			department.setParent(null);
			departmentService.deleteDepartment(department);
			ajaxMsg.setSuccess(true);
		}
		catch (ServiceException e)
		{
			ajaxMsg.setSuccess(false);
			ajaxMsg.setMsg(e.getMessage());
		}
		renderJson(ajaxMsg);
		return NONE;
	}
	
	public String update()
	{
		if(department.getParent().getId()==null)
			department.setParent(null);
		departmentService.updateEntity(department);
		ajaxMsg.setSuccess(true);
		renderJson(ajaxMsg);
		return NONE;
	}
	
	public String findChildrens()
	{
		if(department.getId()==0)
			department=null;
		List<Department> childrens=departmentService.findChildDepartments(department);
		for(Department d:childrens)
		{
			d.setPid(d.getParent()==null?0:d.getParent().getId());
			d.setParent(null);
		}
		renderJson(childrens);
		return NONE;
	}

	public String departmentUsers()
	{
		Pager<User> users=departmentService.findDepartmentUsers(department);
		renderJson(users);
		return NONE;
	}
}
